package com.landi.logger.utils;

import org.slf4j.LoggerFactory;

import java.nio.charset.Charset;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.rolling.RollingFileAppender;
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy;

/**
 * @author chenxumeng
 * @description
 */
public class LoggerUtil {
    /**应用日志路径**/
    private static final String appFile = "/sdcard/AndroidLogback/TestLog/app/app.log";
    private static final String appHistory = "/sdcard/AndroidLogback/TestLog/app/app.%d{yyyy-MM-dd}_%i.zip";
    private static  Logger logger = null;
    public static Logger getLogger(){
        return logger;
    }

    public static void d(String tag,String msg){
        logger.debug(tag,msg);
    }

    public static void init() {
        LoggerContext loggerContext = (LoggerContext) LoggerFactory.getILoggerFactory();
        //设置文件输出 <appender class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy/>
        RollingFileAppender<ILoggingEvent> rollingFileAppender = new RollingFileAppender<ILoggingEvent>();
        rollingFileAppender.setContext(loggerContext);
        rollingFileAppender.setAppend(true);
        //相当 appender name这个字节
        rollingFileAppender.setName("appLog");
        rollingFileAppender.setFile(appFile);

        TimeBasedRollingPolicy rollingPolicy = new TimeBasedRollingPolicy<>();
        //按天进行文件切换
        rollingPolicy.setFileNamePattern(appHistory);
        rollingPolicy.setMaxHistory(3);
        rollingPolicy.setContext(loggerContext);
        rollingPolicy.setParent(rollingFileAppender);
        rollingPolicy.start();
        rollingFileAppender.setRollingPolicy(rollingPolicy);

        //按文件大小进行切换

        /**
         * 设置输出的信息格式
         *      <encoder>
         *       <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36}: %msg%n</pattern>
         *       <immediateFlush>true</immediateFlush>
         *     </encoder>
         */
        PatternLayoutEncoder encoder = new PatternLayoutEncoder();
        encoder.setPattern("%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36}: %msg%n");
        encoder.setCharset(Charset.forName("UTF-8"));
        encoder.setImmediateFlush(true);
        encoder.setContext(loggerContext);
        encoder.start();
        rollingFileAppender.setEncoder(encoder);

        rollingFileAppender.start();

        Logger rootLogger = loggerContext.getLogger("ROOT");
        rootLogger.setLevel(Level.DEBUG);
        rootLogger.addAppender(rollingFileAppender);
        logger = rootLogger;
    }
}
